package com.mming.sso.filter;

import com.mming.sso.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class TokenFilter extends BaseFilter {
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String username = request.getParameter("username");
        //获取cookie里面的token
        String token = getTokenFromCookie(request);
        //获取redis中存储的对应用户token
        String tokenKey = TokenUtil.generateLoginKey(username);
        String storedToken = redisTemplate.opsForValue().get(tokenKey);
        //判断两个token中有没有空并且比较两个token
        if (token == null || !token.equals(storedToken)) {
            outputResponse(400, response);
        } else {
            //判断token是否有效 有效放行，无效返回权限不足
            if (TokenUtil.verify(token, username, TokenUtil.SECRET))
                filterChain.doFilter(servletRequest, servletResponse);
            else
                outputResponse(403, response);
        }
    }

    private String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("_tk"))
                return cookie.getValue();
        }
        return null;
    }
}
